from sqlalchemy.orm import Session

from core.entity.do.models import CmsAlertRule
from core.entity.vo.view_models import CmsAlertRuleVO


class CmsAlertRuleDao:
    """
    高德终端dao
    """

    @classmethod
    def get_cms_alert_rule_by_id(cls, db: Session, id: int):
        """
        根据id查询高德终端信息
        :param db: orm对象
        :param id: 主键ID
        :return: 高德终端信息对象
        """
        cms_alert_rule = db.query(CmsAlertRule) \
            .filter(CmsAlertRule.id == id) \
            .first()

        return cms_alert_rule

    @classmethod
    def get_cms_alert_rule_by_fence_id(cls, db: Session, fence_id: str, rule_type: str):
        """
        根据终端id查询高德终端信息
        :param db: orm对象
        :param fence_id: 终端id
        :param rule_type: 类型
        :return: 高德终端信息对象
        """
        cms_alert_rule = db.query(CmsAlertRule) \
            .filter(CmsAlertRule.fence_id == fence_id and CmsAlertRule.type == rule_type) \
            .first()

        return cms_alert_rule

    @classmethod
    def get_cms_alert_rule_like_name(cls, db: Session, rule_name: str):
        """
        获取所有的参数配置信息
        :param db: orm对象
        :param rule_name: 终端名称
        :return: 高德终端信息对象集合
        """
        cms_alert_rule_list = db.query(CmsAlertRule) \
            .filter(CmsAlertRule.rule_name.like(f'%{rule_name}%') if rule_name else True) \
            .all()

        return cms_alert_rule_list

    @classmethod
    def add_cms_alert_rule_dao(cls, db: Session, cms_alert_rule: CmsAlertRuleVO):
        """
        新增高德终端
        :param db: orm对象
        :param cms_alert_rule: 高德终端对象
        :return:
        """
        model_dict = CmsAlertRule(**cms_alert_rule.dict())
        db.add(model_dict)
        db.flush()

        return model_dict

    @classmethod
    def edit_cms_alert_rule_dao(cls, db: Session, cms_alert_rule: dict):
        """
        编辑参数配置数据库操作
        :param db: orm对象
        :param cms_alert_rule: 需要更新的参数配置字典
        :return:
        """
        db.query(CmsAlertRule) \
            .filter(CmsAlertRule.id == cms_alert_rule.get('id')) \
            .update(cms_alert_rule)

    @classmethod
    def delete_cms_alert_rule_dao(cls, db: Session, id: int):
        """
        编辑参数配置数据库操作
        :param db: orm对象
        :param id: id
        :return:
        """
        db.query(CmsAlertRule) \
            .filter(CmsAlertRule.id == id) \
            .delete()
